import {Injectable} from '@angular/core';
import {HttpClient, HttpParams, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  private http: any;
  public currentHost: any;

  commomHttpHeaders = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json; charset=UTF-8',
      'Access-Control-Allow-Origin': '*'
    })
  };

  constructor(private Http: HttpClient) {
    this.http = Http;
  }

  setHost(host): void {
    this.currentHost = host;
  }

  // get方法
  public get(url: string, options?: Object, params?: Object): Observable<{}> {
    let httpParams = new HttpParams();
    if (params) {
      for (const key in params) {
        if (params[key] === false || params[key]) {
          httpParams = httpParams.set(key, params[key]);
        }
      }
    }
    return this.http.get(url, {
      headers: Object.assign(this.commomHttpHeaders, options),
      params: httpParams
    }).pipe(catchError(this.handleError));
  }

  // post方法
  public post(url: string, body: any = null, options?: Object): Observable<{}> {
    return this.http.post(url, body, Object.assign(this.commomHttpHeaders, options)).pipe(catchError(this.handleError));
  }

  // put方法
  public put(url: string, body: any = null, options?: Object): Observable<{}> {
    return this.http.put(url, body, Object.assign(this.commomHttpHeaders, options)).pipe(catchError(this.handleError));
  }

  // delete方法
  public delete(url: string, body: any = null, options?: Object): Observable<{}> {
    return this.http.delete(url, body, Object.assign(this.commomHttpHeaders, options)).pipe(catchError(this.handleError));
  }

  // post表单
  public postForm(url: string, body: any = null, options?: Object): Observable<{}> {
    let httpParams = new HttpParams();
    if (body) {
      for (const key in body) {
        if (body[key] === false || body[key]) {
          httpParams = httpParams.set(key, body[key]);
        }
      }
    }
    return this.http.post(url, httpParams, options).pipe(catchError(this.handleError));
  }

  /**
   * 处理请求失败的错误
   * @param error HttpErrorResponse
   */
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    console.log(error);
    return throwError(error.error);
  }
}
